package com.isesol.ime.rest.controller;

import com.alibaba.fastjson.*;
import com.isesol.ime.service.*;
import org.slf4j.*;
import org.springframework.web.bind.annotation.*;

import javax.annotation.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.util.zip.*;

@RestController
public class DownloadController{

	protected Logger LOGGER = LoggerFactory.getLogger(getClass());

	@Resource
	DownloadService eventService;

	private void getDownload(HttpServletResponse response, byte[] bytes,String filename){

		ServletOutputStream sos;
		try{
//			HashCode hashCode=Hashing.md5().hashBytes(bytes);
//			hashCode.asLong();

			sos = response.getOutputStream();
			ZipOutputStream out = new ZipOutputStream(sos);
			out.putNextEntry(new ZipEntry(filename));
			out.write(bytes);
			response.setContentType("application/zip");
			response.addHeader("Content-Disposition", "attachment; filename=data.zip");
			out.finish();
			out.close();
		} catch (IOException e){

			LOGGER.error("getDownload error",e);
		}
	}

	@ResponseBody
	@RequestMapping("/download/{subId}")
	public void event(@PathVariable long subId,HttpServletResponse response){

		LOGGER.info("download subId={}",subId);
		Map eventMap = eventService.getData(subId);

		getDownload(response, JSON.toJSONString(eventMap).getBytes(),eventMap.get("fileName").toString());

	}

}
